<template>
  <div class="app-container">
    <el-form
      ref="form"
      :model="form"
      :rules="rules"
      label-width="120px"
      style="padding-left: 50px;padding-right: 50px;">
      <el-row style="margin-top: 20px;">
        <el-col :span="8">
          <el-form-item label-width="60px" label="Email" prop="toMail">
            <el-input disabled v-model="form.toMail" placeholder="" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label-width="60px" label="Subject" prop="title">
            <el-input v-model="form.title" placeholder="" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <span style="color: #333;font-size: 12px;">附件</span>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-upload
            :action="uploadUrl"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            :before-remove="beforeRemove"
            accept=".pdf,.doc,.docx"
            name="file"
            :headers="headers"
            multiple
            :limit="100"
            ref="upload"
            :on-exceed="handleExceed"
            :on-success="handleFileSuccess"
            :file-list="form.fileList">
            <div style="display: flex;align-items: center;">
              <i class="el-icon-upload" style="font-size: 35px;"></i>
              <span style="color: #99a9bf;font-size: 15px;margin-left: 2px;">Upload</span>
            </div>
            <!--<el-button size="small" type="primary">点击上传</el-button>-->
            <div slot="tip" class="el-upload__tip">Format pdf/word/excel</div>
          </el-upload>
        </el-col>
      </el-row>
      <el-row style="margin-top: 55px;">
        <el-button
          type="primary"
          plain
          size="mini"
          @click="importTemplate"
        >Import Template</el-button>
        <el-col :span="24" style="margin-top: 10px;">
          <el-form-item label-width="0" label="">
            <editor v-model="form.content" :min-height="392"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div v-if="isConfirm" style="display: flex;width: 100%;">
      <el-button type="primary" @click="submitForm" style="margin-left: 50px;">Confirm</el-button>
      <el-button @click="cancel" style="margin-left: 10px;">Cancel</el-button>
    </div>

  </div>
</template>

<script>
  import { listMail, getMail, delMail, addMail, updateMail } from "@/api/system/mail";
  import { listCandidate, getCandidate, delCandidate, addCandidate, updateCandidate } from "@/api/system/candidate";
  import { listTem, getTem, delTem, addTem, updateTem } from "@/api/system/tem";
  import { getToken } from "@/utils/auth";



export default {
  name: "CandidateAdd",
  data() {
    return {
      isConfirm: true,
      type: 0,
      isMainlang: false,
      isHK: false,
      // 选中数组
      openFile: false,
      openFileDoc: false,
      vHtml: "",
      wordURL:'',  //文件地址，看你对应怎末获取、赋值
      id: null,
      mailId: null,
      ids: [],
      statusT: 0,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 【请填写功能名称】表格数据
      candidateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      uploadUrl: "http://jobslink.megaslink.com/prod-api" + "/common/upload", // process.env.VUE_APP_BASE_API上传的图片服务器地址
      headers: {
        Authorization: "Bearer " + getToken()
      },
      formJobs: {},
      ruleJobs: {
        com: [
          { required: true, message: "company null", trigger: "blur" }
        ],
        title: [
          { required: true, message: "title null", trigger: "blur" }
        ],
      },
      queryParamsEmail: {
        id: null,
        pageNum: 1,
        pageSize: 10,
      },
      // 查询参数
      queryParams: {
        id: null,
        pageNum: 1,
        pageSize: 10,
        email1: null,
        email2: null,
        name: null,
        phone1: null,
        phone2: null,
        gender: null,
        salary: null,
        education: null,
        other: null,
        district: null,
        age: null,
        birthyear: null
      },
      fileData: {name: 'food.jpeg', url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'},
      // 表单参数
      form: {
        id: null,
        userId: null,
        fromMail: null,
        toMail: null,
        candId: null,
        title: null,
        content: null,
        filePath: null,
        type: 0,
        sendTime: null,
        createTime: null,
        updateTime: null,
        createBy: null,
        updateBy: null,
        fileList: []
      },
      formEmail: {
        id: null,
        email1: null,
        email2: null,
        name: null,
        phone1: null,
        phone2: null,
        gender: null,
        salary: null,
        education: null,
        other: null,
        district: null,
        area: null,
        cnAddr: null,
        age: null,
        birthyear: null,
        filePath: null,
        fileList: []
      },
      // 表单校验
      rules: {
        email1: [
          { required: true, message: "email is null", trigger: "blur" }
        ],
        name: [
          { required: true, message: "name is null", trigger: "blur" }
        ],
        phone1: [
          { required: true, message: "phone is null", trigger: "blur" }
        ],
      },
      pdfUrl: null,
      pageTotal: null
    };
  },
  // 给Vue的实例注入数据，进行数据监听
  created() {
    console.log("created");
    this.id = this.$route.query.id;
    this.type = this.$route.query.type;
    this.mailId = this.$route.query.mailId;
    this.statusT = this.$route.query.statusT;
    if (this.id == null || this.id == '' || this.id  == undefined) {
      if (this.mailId == null || this.mailId == '' || this.mailId  == undefined){
        this.$nextTick(() => {
          this.scrollToTop();
        })
      } else {
        this.isConfirm = false;
        this.queryParamsEmail.id = this.mailId;
        this.getEmailList();
      }
    } else {
      this.queryParams.id = this.id;
      this.getList();
    }
  },
  methods: {
    scrollToTop() {
      window.scrollTo({
        top: 0,
        behavior: "smooth"
      });
    },
    handleRemove(file, fileList) {
      console.log(file);
      console.log(fileList);
      if (file.status == "success") {
        this.form.fileList = this.form.fileList.filter(item => {
          return !(item.name == file.name && item.url == file.url);
        } );
      }
      console.log(this.form.fileList);
    },
    handlePreview(file) {
      console.log(file);
      // 截取上传文件的后缀名
      let fileType = file.name.substring(file.name.lastIndexOf(".") + 1);
      console.log(fileType);
      // 判断文件名的类型，允许多种就判断多个
      if (fileType.toLocaleLowerCase() == 'pdf' || fileType.toLocaleLowerCase() == 'doc' ||
        fileType.toLocaleLowerCase() == 'docx' || fileType.toLocaleLowerCase() == 'xlsx' ||
        fileType.toLocaleLowerCase() == 'xls') {
        let Base64 = require('js-base64').Base64
        window.open('http://www.megaslink.com:8012/onlinePreview?url='+encodeURIComponent(Base64.encode(this.form.filePath)));
      } else {
        this.$message.warning("文件类型必须为pdf,doc,docx,xlsx,xls格式");
        // 返回false 就不会执行上传操作了
        return false;
      }
    },
    handleExceed(files, fileList) {
      // this.$message.warning(`当前限制只能上传 1 个文件或者删除重新上传`);
    },
    handleFileSuccess(response, file, fileList) {
      console.log(response);
      console.log(file);
      console.log(fileList);
      if (response.code == 200) {
        console.log("================" + response.url);
        this.form.filePath = response.url;
        this.form.fileList.push( {
            name: file.name,
            url: response.url
          }
        )
        console.log(this.form.fileList);
      } else {
        this.$message.warning(`上传失败`);
        // this.form.fileList.splice(this.form.fileList.length - 1, 1);
      }
      // fileList[0].response.url;

    },
    beforeRemove(file, fileList) {
      return this.$confirm(`Remove ${ file.name }？`);
    },
    importTemplate() {
      this.$modal.loading("loading...");
      listTem().then(response => {
        let temList = response.rows;
        if (temList != null && temList.length > 0) {
          this.form.content = temList[0].content;
        }
      }).finally(f => {
        this.$modal.closeLoading();
      });
    },
    getEmailList() {
      this.$modal.loading("loading...");
      listMail(this.queryParamsEmail).then(response => {
        if (response.rows != null) {
          this.form = response.rows[0];
          this.form.fileList = [];
          if (this.form.filePath != null && this.form.filePath != '') {
            this.form.fileListPath = this.form.filePath.split(",");
            for (let i = 0; i < this.form.fileListPath.length; i++) {
              this.form.fileList.push({
                name: this.form.fileListPath[i].substring(this.form.filePath.lastIndexOf('/') + 1),
                url: this.form.fileListPath[i]
              });
            }
          }
        }
        this.$nextTick(() => {
          this.scrollToTop();
        })
      }).finally(f => {
        this.$modal.closeLoading();
      });
    },
    /** 查询【请填写功能名称】列表 */
    getList() {
      this.$modal.loading("loading...");
      listCandidate(this.queryParams).then(response => {
        this.candidateList = response.rows;
        if (this.candidateList != null) {
          this.formEmail = this.candidateList[0];
          this.form.toMail = this.formEmail.email1;
          this.form.candId = this.formEmail.id;
          // this.form.fileList = [];
          // if (this.form.filePath != null && this.form.filePath != '') {
          //   this.form.fileListPath = this.form.filePath.split(",");
          //   for (let i = 0; i < this.form.fileListPath.length; i++) {
          //     this.form.fileList.push({
          //       name: this.form.fileListPath[i].substring(this.form.filePath.lastIndexOf('/') + 1),
          //       url: this.form.fileListPath[i]
          //     });
          //   }
          // }
        }
        this.$nextTick(() => {
          this.scrollToTop();
        })
        this.$modal.closeLoading();
      });
    },
    // 取消按钮
    cancel() {
      if(this.type == 1) {
        const obj = { path: "/receive", name: "Receive" };
        this.$tab.closePage(obj);
        setTimeout(()=> {
          this.$router.push({path:'/receive'})
        }, 300);
      } else {
        const obj = { path: "/mail", name: "Mail" };
        this.$tab.closePage(obj);
        setTimeout(()=> {
          const obj = { path: "/mail" };
          this.$tab.closeOpenPage(obj);
        }, 300);
      }
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        email1: null,
        email2: null,
        name: null,
        phone1: null,
        phone2: null,
        gender: null,
        salary: null,
        education: null,
        other: null,
        district: null,
        age: null,
        birthyear: null
      };
      this.resetForm("form");
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.filePath = '';
          if (this.form.fileList != null && this.form.fileList.length > 0) {
            for (let i = 0; i < this.form.fileList.length; i++) {
              if (i == (this.form.fileList.length - 1)) {
                this.form.filePath = this.form.filePath + this.form.fileList[i].url;
              } else {
                this.form.filePath = this.form.filePath + this.form.fileList[i].url + ",";
              }
            }
          }
          this.form.type = 0;
          if (this.form.id != null) {
            updateMail(this.form).then(response => {
              this.$modal.msgSuccess("success");
              const obj = { path: "/mail", name: "Mail" };
              this.$tab.closePage(obj);
              setTimeout(()=> {
                const obj = { path: "/mail" };
                this.$tab.closeOpenPage(obj);
              }, 300);
            });
          } else {
            addMail(this.form).then(response => {
              this.$modal.msgSuccess("success");
              const obj = { path: "/mail", name: "Mail" };
              this.$tab.closePage(obj);
              setTimeout(()=> {
                const obj = { path: "/mail" };
                this.$tab.closeOpenPage(obj);
              }, 300);
            });
          }
        }
      });
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss">
  .card3 {
    background-image: linear-gradient(to right, #000 35%, rgba(255,255,255,0) 0%); /* 35%设置虚线点x轴上的长度 */
    background-position: bottom; /* top配置上边框位置的虚线 */
    background-size: 10px 1px; /* 第一个参数设置虚线点的间距；第二个参数设置虚线点y轴上的长度 */
    background-repeat: repeat-x;
  }
  .ql-editor.ql-blank::before{
    content: "";
  }
</style>
